package com.xbongbong.paas.lowcode.impl;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.lowcode.PaasFormServiceRegistrationService;
import com.xbongbong.paas.model.PaasFormServiceModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.domain.entity.PaasFormServiceEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formservice.pojo.FormServicePojo;
import com.xbongbong.pro.formservice.pojo.ParamValuePojo;
import com.xbongbong.pro.formservice.pojo.dto.FormServiceListDTO;
import com.xbongbong.pro.formservice.pojo.dto.FormServiceSaveDTO;
import com.xbongbong.pro.formservice.pojo.vo.FormServiceListVO;
import com.xbongbong.pro.formservice.pojo.vo.FormServiceSaveVO;
import com.xbongbong.saas.constant.StringConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/03/09 15:14
 */
@Service("paasFormServiceRegistrationService")
public class PaasFormServiceRegistrationServiceImpl implements PaasFormServiceRegistrationService {

    private static final Logger LOG = LoggerFactory.getLogger(PaasFormServiceRegistrationServiceImpl.class);

    @Resource
    private PaasFormServiceModel paasFormServiceModel;


    @Override
    public FormServiceListVO list(FormServiceListDTO formServiceListDTO) throws XbbException {
        try {
            FormServiceListVO formServiceListVO = new FormServiceListVO();
            String corpid = formServiceListDTO.getCorpid();
            Long formId = formServiceListDTO.getFormId();
            Integer businessType = formServiceListDTO.getBusinessType();
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(StringConstant.FORM_ID, formId);
            param.put(StringConstant.BUSINESS_TYPE, businessType);
            param.put("orderByStr", "sort ASC");
            List<PaasFormServiceEntity> serviceList = paasFormServiceModel.findEntitys(param);
            if (CollectionsUtil.isEmpty(serviceList)) {
                formServiceListVO.setServiceList(new ArrayList<>());
                return formServiceListVO;
            }
            List<FormServicePojo> result = new ArrayList<>();
            for (PaasFormServiceEntity paasFormServiceEntity : serviceList) {
                FormServicePojo formServicePojo = new FormServicePojo(paasFormServiceEntity.getId(), paasFormServiceEntity.getName(), paasFormServiceEntity.getCommitFlag(), paasFormServiceEntity.getEditFlag(), paasFormServiceEntity.getDeleteFlag(),
                        paasFormServiceEntity.getCommitServiceId(), JSON.parseArray(paasFormServiceEntity.getCommitServiceParam(), ParamValuePojo.class), paasFormServiceEntity.getEditServiceId(), JSON.parseArray(paasFormServiceEntity.getEditServiceParam(), ParamValuePojo.class),
                        paasFormServiceEntity.getDeleteServiceId(), JSON.parseArray(paasFormServiceEntity.getDeleteServiceParam(), ParamValuePojo.class), paasFormServiceEntity.getSort());
                result.add(formServicePojo);
            }
            formServiceListVO.setServiceList(result);
            return formServiceListVO;
        } catch (Exception e) {
            LOG.error("paasFormServiceRegistrationServiceImpl.list 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public FormServiceSaveVO save(FormServiceSaveDTO formServiceSaveDTO) throws XbbException {
        try {
            String corpid = formServiceSaveDTO.getCorpid();
            Long formId = formServiceSaveDTO.getFormId();
            Integer saasMark = formServiceSaveDTO.getSaasMark();
            Integer businessType = formServiceSaveDTO.getBusinessType();
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(StringConstant.FORM_ID, formId);
            param.put(StringConstant.BUSINESS_TYPE, businessType);
            List<PaasFormServiceEntity> serviceList = paasFormServiceModel.findEntitys(param);
            List<Long> deleteIdList = new ArrayList<>();
            List<Long> updateIdList = new ArrayList<>();
            serviceList.forEach(item->{
                deleteIdList.add(item.getId());
            });
            String userId = formServiceSaveDTO.getUserId();
            List<FormServicePojo> formServiceList = formServiceSaveDTO.getFormServiceList();
            List<PaasFormServiceEntity> addList = new ArrayList<>();
            List<PaasFormServiceEntity> updateList = new ArrayList<>();
            formServiceList.forEach(item->{
                long now = DateTimeUtil.getInt();
                if (Objects.isNull(item.getId())) {
                    PaasFormServiceEntity paasFormServiceEntity = new PaasFormServiceEntity(corpid, formId, saasMark, businessType, item.getName(), item.getCommitFlag(), item.getEditFlag(), item.getDeleteFlag(), item.getCommitServiceId(), JSON.toJSONString(item.getCommitServiceParam()),
                            item.getEditServiceId(), JSON.toJSONString(item.getEditServiceParam()), item.getDeleteServiceId(),JSON.toJSONString( item.getDeleteServiceParam()), item.getSort(), userId, now, now);
                    addList.add(paasFormServiceEntity);
                } else {
                    PaasFormServiceEntity paasFormServiceEntity = new PaasFormServiceEntity(item.getId(), item.getName(), item.getCommitFlag(), item.getEditFlag(), item.getDeleteFlag(), item.getCommitServiceId(), JSON.toJSONString(item.getCommitServiceParam()),
                            item.getEditServiceId(), JSON.toJSONString(item.getEditServiceParam()), item.getDeleteServiceId(),JSON.toJSONString( item.getDeleteServiceParam()), item.getSort(), now);
                    updateList.add(paasFormServiceEntity);
                    updateIdList.add(item.getId());
                }
            });

            if (CollectionsUtil.isNotEmpty(addList)) {
                paasFormServiceModel.addBatch(addList);
            }

            if (CollectionsUtil.isNotEmpty(updateList)) {
                paasFormServiceModel.updateBatch(updateList, corpid);
            }
            deleteIdList.removeAll(updateIdList);
            if (CollectionsUtil.isNotEmpty(deleteIdList)) {
                paasFormServiceModel.deleteBatch(deleteIdList, corpid);
            }
            return new FormServiceSaveVO();
        }catch (Exception e) {
            LOG.error("paasFormServiceRegistrationServiceImpl.save 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
